/**
 * Created by cgf
 */


$('#picker').change(function () {
    if ($(this).val() == 0) {
        $('#search').attr('placeholder', '请输入磁盘名称精确查询');
    } else {
        $('#search').attr('placeholder', '此状态下的磁盘名称');
    }
});

var DateDiff   = function (strDateStart, strDateEnd) {
    var strSeparator  = "-"; //日期分隔符
    var strDateArrayStart;
    var strDateArrayEnd;
    var intDay;
    strDateArrayStart = strDateStart.split(strSeparator);
    strDateArrayEnd   = strDateEnd.split(strSeparator);
    var strDateS      = new Date(strDateArrayStart[0] + "/" + strDateArrayStart[1] + "/" + strDateArrayStart[2]);
    var strDateE      = new Date(strDateArrayEnd[0] + "/" + strDateArrayEnd[1] + "/" + strDateArrayEnd[2]);
    intDay            = (strDateE - strDateS) / (1000 * 3600 * 24);
    return intDay;
};
var formatDate = function (uData) {
    var myDate = new Date(uData * 1000);
    var year   = myDate.getFullYear();
    var month  = myDate.getMonth() + 1;
    var day    = myDate.getDate();
    return year + '-' + month + '-' + day;
};

function expan_price(size, expire) {
    var myDate                                          = new Date().getTime();
    var nowDate = formatDate(myDate / 1000), expireDate = formatDate(expire);
    var expan_size                                      = $('#expan-size').val(),
        timeDiffer                                      = DateDiff(nowDate, expireDate),
        total_price                                     = ((expan_size - size) / 30) * timeDiffer;
    $('#expan-money').html(Math.floor(total_price * 10) / 10);
}
window.alertMessage = function(msg){
    $('#alert_warning_msg').html(msg);
    $('.navbar-container .alert-warning').show();
};
function verifyCode() {
    $.getJSON(urls.sendCode, function (res) {
        console.log(res.msg);
    })
}

var getStatus = function () {
    var a = function () {
        $.getJSON(urls.status, {sn: needGetStatus}, function (dt) {
            if (dt.error * 1 != 1) {
                for (var i in dt.data) {
                    if(dt.data[i].result && dt.data[i].result == 4 && dt.data[i].status == 3){
                        $('#status_' + dt.data[i].sn).html('<span class="label label-danger">挂载失败</span>');
                        alertMessage('磁盘挂载失败，请联系售后技术！');
                    }else{
                        $('#status_' + dt.data[i].sn).html(qystatus[dt.data[i].status]);
                    }
                }
            }
            window.setTimeout(getStatus, 3000);
        });
    };
    a();
    return a;
}();

var cloud_load = function () {
    var that = {};
    $('.btn-load').click(function () {
        that.sn     = $(this).attr('data-sn');
        that.tag    = $(this).attr('data-tag');
        that.status = $('#status_' + that.sn).html();
        $('#loadModel').modal();
    });
    $('#loadModel').on('show.bs.modal', function () {
        $('#mount-name').val(that.tag);
        $.getJSON(urls.load, {sn: that.sn}, function (res) {
            var html_str = '';

            if (res.error * 1 != 1 && res.data != '') {
                var obj = res.data;
                for (var x in obj) {
                    html_str += '<option value="' + obj[x].sn + '">' + obj[x].tag + '</option>';
                }
                $('#mount-ins').html(html_str).selectpicker({
                    // style: 'btn-info',
                    size: 4
                });
            } else {
                $('#mount-ins').remove();
                alert(res.msg);
                $('#mount-footer').remove();
            }
        })
    });
    $('#mount-submit').click(function () {
        var ins      = $('#mount-ins').val();
        var is_fllow = $('#mount-follow').val();
        $('#status_' + that.sn).html('<span class="load-icon">' + qystatus['3']);
        $.getJSON(urls.load, {sn: that.sn, ins: ins, is_fllow: is_fllow}, function (res) {
            if (res.error == 1) {
                alert(res.msg);
                //$('#messageModel').modal();
                $('#status_' + that.sn).html(that.status);
            } else {
                alert('磁盘挂载成功！');
                //$('#messageModel').modal();
                $('#status_' + that.sn).html(qystatus['4']);
                $('#mount-' + that.sn).addClass('btn-disabled');
                $('#unmount-' + that.sn).removeClass('btn-disabled');
            }
            $('#loadModel').modal('hide');
        })
    })
}();

var unmount  = function () {
    var that = {};
    $('.btn-unmount').click(function () {
        that.sn     = $(this).attr('data-sn');
        that.tag    = $(this).attr('data-tag');
        that.status = $('#status_' + that.sn).html();
        $('#unmountModel').modal();
    });
    $('#unmountModel').on('show.bs.modal', function () {
        $('#unmount-name').html(that.tag);
    });
    $('#unmount-submit').click(function () {
        var ins = $('#mount-ins').val();
        $('#status_' + that.sn).html('<span class="load-icon"></span>' + qystatus['5']);
        $.getJSON(urls.unmount, {sn: that.sn}, function (res) {
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
                $('#status_' + that.sn).html(that.status);
            } else {
                $('#msg-box').html('磁盘卸载成功！');
                $('#messageModel').modal();
                $('#status_' + that.sn).html(qystatus['2']);
                $('#unmount-' + that.sn).addClass('btn-disabled');
                $('#mount-' + that.sn).removeClass('btn-disabled');
            }
            $('#unmountModel').modal('hide');
        })
    })
}();
var snapshot = function () {
    var that = this;
    $('.btn-snapshot').click(function () {
        that.sn     = $(this).attr('data-sn');
        that.tag    = $(this).attr('data-tag');
        that.status = $('#status_' + that.sn).html();
        $('#snapshotModel').modal();
    });
    $('#snapshotModel').on('show.bs.modal', function () {
        $('#snapshot-storname').text(that.tag);
        $.getJSON(urls.snapshot, {sn: that.sn}, function (res) {
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
                $('#snapshotModel').modal('hide');
            } else {
                $('#snapshot-storattr').html(qyattr[res.data.attribute]);
                $('#snapshot-name').val(res.data.tag);
            }
        })
    });
    $('#snapshot-submit').click(function () {
        var snapshot = $('#snapshot-name').val();
        if (snapshot.length < 2 || snapshot.length > 128) {
            alert('快照名称为2-128个字符');
            return false;
        }
        $('#status_' + that.sn).html('<span class="load-icon"></span>' + qystatus['1']);
        $.getJSON(urls.snapshot, {sn: that.sn, snapshot: snapshot, act: 'sub'}, function (res) {
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
            } else {
                $('#msg-box').html('创建成功');
                $('#messageModel').modal();
            }
            $('#status_' + that.sn).html(that.status);
            $('#snapshotModel').modal('hide');
        })

    })
}();


var expansion = function () {
    var that = this;
    $('.btn-expansion').click(function () {
        that.sn     = $(this).attr('data-sn');
        that.tag    = $(this).attr('data-tag');
        that.status = $('#status_' + that.sn).html();
        $('#expan-money').html(0);
        $('#expanModel').modal();

    });
    $('#expanModel').on('show.bs.modal', function () {
        $('#expansion-name').text(that.tag);
        $.getJSON(urls.expansion, {sn: that.sn}, function (res) {
            that.size   = parseInt(res.data.size);
            that.expire = res.data.ended;
            $('#expan-size').val(that.size);
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
                $('#expanModel').modal('hide');
            } else {
                //$('#expan-money').html(res.data.price*res.data.size);
                $('#expan-acount-money').html(parseFloat(res.account));
            }

        })

    });
    $('#expan-submit').click(function () {
        var expan_size = $('#expan-size').val();
        if (expan_size == that.size) {
            alert('请选择容量');
            return;
        }
        if (!confirm('您下单成功后，需要您通过ECS控制台重启本磁盘挂载的实例。扩容生效后，需要登录到VM内部，手动格式化以便扩展存储空间')) return false;
        $('#status_' + that.sn).html('<span class="loading">扩容中</span>');
        $.getJSON(urls.expansion, {sn: that.sn, expan_size: expan_size}, function (res) {
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
            } else {
                $('#msg-box').html('<span class="text-danger">扩容成功！</span> 您下单成功后，如果是待挂载中的磁盘，挂载到实例上可即刻生效无需重启；如果磁盘已挂载在实例上，需要您通过ECS控制台重启本磁盘挂载的ECS实例，磁盘扩容才能生效。');
                $('#messageModel').modal();
            }
            $('#status_' + that.sn).html(that.status);
            $('#expanModel').modal('hide');
        })
    });
    $('.jia').click(function () {
        var gb = parseInt($(this).parents('.good-num-ct').find('input').val());
        gb++;
        if (gb > 1024) gb = 1024;
        $('#expan-size').val(gb);
        expan_price(that.size, that.expire);
    })
    $('.jian').click(function () {
        var gb = parseInt($(this).parents('.good-num-ct').find('input').val());
        gb--;
        if (gb < that.size) gb = that.size;
        $('#expan-size').val(gb);
        expan_price(that.size, that.expire);
    })
    $('#expan-size').change(function () {
        var vlid = /^[0-9]*[1-9][0-9]*$/;
        if (vlid.test($(this).val())) {
            var vl = parseInt($(this).val());
            if (vl > 1024) $(this).val(1024);
            if (vl < that.size) $(this).val(that.size);
        } else {
            $(this).val(that.size);
        }
        expan_price(that.size, that.expire);
    })
}();

var del = function () {
    var that = {};
    $('.btn-del').click(function () {
        that.sn = $(this).attr('sn');
        $('#del-name').text($(this).attr('sname'));
        $('#delModel').modal();
    });
    $('#del-send').on('click', function () {
        alert('正在发送验证码......');
        //setTimeout("$('#messageModel').modal('hide')",3000);
        verifyCode();
    });
    $('#del-submit').click(function () {
        /*var code = $('#del-code').val().trim();
         if(code == ''){
         alert('验证码不能为空');
         return false;
         }*/
        $.getJSON(urls.del, {sn: that.sn}, function (res) {
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
            } else {
                $('#msg-box').html('成功删除！');
                $('#messageModel').modal();
                window.location.reload();
            }
            $('#delModel').modal('hide');

        })
    })
}();

var renew = function () {
    var that = {};
    $('.btn-renew').click(function () {
        that.sn     = $(this).attr('data-sn');
        that.tag    = $(this).attr('data-tag');
        that.status = $('#status_' + that.sn).html();
        $('#renewModel').modal();

    });
    $('#renewModel').on('show.bs.modal', function () {
        $('#renew-name').text(that.tag);
        $.getJSON(urls.renew, {sn: that.sn}, function (res) {
            that.unit_price = res.unit_price;
            that.size       = res.data.size;
            that.mouth      = $('#charge-cycle .active').val();
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
                $('#renewModel').modal('hide');
            } else {
                cal_price();
                $('#renew-acount-money').html(res.account);
            }

        });
        $('.renewmouth').click(function () {
            $('#charge-cycle .active').removeClass('active');
            $(this).addClass('active');
            that.mouth = $(this).val();
            cal_price();
        });
    });
    $('#renew-submit').click(function () {
        $('#status_' + that.sn).html('<span class="loading">续费中</span>');
        $.getJSON(urls.renew, {sn: that.sn, renewmouth: that.mouth}, function (res) {
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
                $('#status_' + that.sn).html(that.status);
            } else {
                $('#msg-box').html('续费成功！');
                $('#messageModel').modal();
                $('#status_' + that.sn).html(qystatus['2']);
            }
            $('#renewModel').modal('hide');
        })
    });
    function cal_price() {
        var total_price = that.mouth * that.unit_price * that.size;
        $('#renew-money').text(total_price.toFixed(2));
    }
}();


var describe = function () {
    var that = this;
    $('#describeModel').on('show.bs.modal', function () {
        $.getJSON(urls.desc, {sn: that.sn}, function (res) {
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
                $('#describeModel').modal('hide');
            } else {
                $('#desc-desc').val(res.data.desc);
            }
        });
    });

    $('.btn-desc').click(function () {
        that.sn  = $(this).attr('data-sn');
        that.tag = $(this).attr('data-tag');
        //$('#desc-name').attr('placeholder', that.tag);
        $('#desc-name').val(that.tag);
        $('#describeModel').modal();
    });

    $('#desc-submit').click(function () {
        var stor_tag  = $('#desc-name').val(),
            stor_desc = $('#desc-desc').val();
        if (stor_tag.length < 6 || stor_tag.length > 30) {
            alert('磁盘名称为6-30个字符');
            return false;
        }
        if (stor_desc.length < 2 || stor_desc.length > 200) {
            alert('磁盘描述为2-200个字符');
            return false;
        }
        $.getJSON(urls.desc, {sn: that.sn, stor_tag: stor_tag, stor_desc: stor_desc}, function (res) {
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
            } else {
                $('#msg-box').html('成功修改磁盘描述');
                $('#messageModel').modal();
                window.location.reload();
            }
            $('#describeModel').modal('hide');

        })

    })
}();

//    $('#search').keydown(function(event){
//        if(event.keyCode == 13){
//            $('#button').submit();
//        }
//    })

/* chy */
var create = function () {
    var order   = {},
        popover = {};
    $('.btn-create').click(function () {
        $('#createModel').modal();
    });
    $('#createModel').on('show.bs.modal', function () {
        $.getJSON(urls.create, {}, function (res) {
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
                $('#createModel').modal('hide');
            } else {
                var obj = res.list, x;
                if (obj.length < 1) {
                    alert("请先购买云服务器！");
                    $('#createModel').modal('hide');
                }
                for (x in obj) {
                    $('#create_instance').append('<option sn="' + obj[x].sn + '" region_id="' + obj[x].region_id + '" region_name="' + obj[x].region_name + '">【 ' + obj[x].contact + obj[x].region_name + ' 】 ' + obj[x].tag + '</option>');
                }
                $('#create_instance').selectpicker({
                    //style: 'btn-info',
                    size: 4
                });
                order.storage_price = res.price;
                $('#create_account').text(res.account * 1);
            }
        })
    });
    //var storage_price = eval("("+ '<?php echo $viewBag->storage_price; ?>' +")"),

    $('#crete_storage_type').selectpicker('ssd', '');
    order.storage_type = 'ssd';
    $('#create_size').val('');
    $('#create_number').val('1');
    $('#create_price').val('');
    $('#create_account').text('0.0');

    $('#create-submit').click(function () {
        if (!order.region_id) {
            return prompt('create_instance_box', '挂载目标不允许为空！');
        }
        //console.log(order.storage_type);
        if (!order.storage_type) {
            return prompt('crete_storagetype_box', '硬盘类型不允许为空！');
        }
        calculate_price();
        var create_size   = $('#create_size').val(),
            create_number = $('#create_number').val(),
            create_month  = $('#create_month').val(),
            storage_type  = $('#crete_storage_type').val(),
            create_price  = $('#create_price').val();
        if ('' == create_size) {
            return prompt('create_size', '容量不允许为空！');
        }
        create_size = create_size *1 ;
        if(isNaN(create_size) || create_size< 5 || create_size>2000){
            return prompt('create_size', '容量不允许为空应在5-2000G之间');
        }
        if ('' == create_number) {
            return prompt('create_number', '数量不允许为空！');
        }
        create_number = create_number * 1;
        if ('' == create_number) {
            return prompt('create_number', '数量应为1-4范围');
        }

        if ($('#create_account').text() * 1 != create_price * 1 && $('#create_account').text() * 1 < create_price * 1) {
            return prompt('create_number', '帐户余额不足，请先充值');
        }

        if (create_month * 1 < 1) {
            return prompt('create_month', '购买时长不能小于1个月');
        }

        var ds = {
            create_size: create_size,
            create_number: create_number,
            create_month: create_month,
            storage_type: storage_type,
            ins_sn: order.ins_sn,
            region_id: order.region_id
        };

        $.getJSON(urls.create, {ds: ds, ac: 'create'}, function (res) {
            if (res.error == 1) {
                $('#msg-box').html(res.msg);
                $('#messageModel').modal();
            } else {
                $('#msg-box').html('云磁盘创建成功！');
                $('#messageModel').modal();
                window.location.reload();
            }
            $('#createModel').modal('hide');
        })
    });

    $("#create_instance").on('changed.bs.select', function () {
        var value = this.value;
        if (!value) {
            delete order.region_id;
            return;
        }
        order.region_id = $("#create_instance option:checked").attr('region_id');
        order.ins_sn    = $("#create_instance option:checked").attr('sn');
        var region_name = $("#create_instance option:checked").attr('region_name');
        $("#create_region").val(region_name);
        calculate_price();
    });

    $("#crete_storage_type").on('changed.bs.select', function () {
        var value          = $("#crete_storage_type option:checked").val();
        order.storage_type = value;
        calculate_price();
    });

    $("#create_month").on('changed.bs.select', function() {
        calculate_price();
    });

    $("#create_size").blur(function () {
        var value = this.value;
        if (!/^(\d+?)$/.test(value) || value < 1) {
            $(this).val(1);
        } else if (value > 2000) {
            $(this).val(2000);
        }
        calculate_price();
    });

    $("#create_number").blur(function () {
        var value = this.value;
        if (!/^(\d+?)$/.test(value) || value < 1) {
            $(this).val(1);
        } else if (value > 4) {
            $(this).val(4);
        }
        calculate_price();
    });

    function calculate_price() {
        if (!order.region_id || !order.storage_type) {
            return;
        }
        var create_size   = $('#create_size').val().trim(),
            create_number = $('#create_number').val().trim(),
            create_month  = $("#create_month").val().trim();
        if ('' == create_size || '' == create_number) {
            return;
        }
        var unit_price = order.storage_price[order.region_id][order.storage_type]['month_price'],
            total      = create_size * unit_price * create_number * create_month;
        $('#create_price').val(total.toFixed(1));
    }

    function prompt(id, msg) {
        // alert('温馨提示：' + msg).set('label', '确定');
        toastr.info(msg, '', {positionClass: "toast-top-center"});
        $("#" + id).focus();
    }
}();




